<template>
	<view style="padding-bottom: 130rpx;">
		<view class="formContainer">
			<uni-forms ref="form">

				<uni-forms-item label="订单号" required>
					<view @click="chooseOrder">
						<u--input v-model="formData.orderNo" placeholder="请选择订单" disabled disabledColor="#fff"
							suffixIcon="arrow-right"></u--input>
					</view>
				</uni-forms-item>
				<uni-forms-item label="车型信息">
					<view>
						<u--input v-model="formData.modelName" placeholder="自动获取车型" disabled></u--input>
					</view>
				</uni-forms-item>
				<uni-forms-item label="租赁时间">
					<view>
						<u--input v-model="formData.time" placeholder="自动获取租赁时间" disabled></u--input>
					</view>
				</uni-forms-item>

				<uni-forms-item label="借调同行" required>
					<view @click="choosePeer">
						<u--input v-model="formData.sameJobName" placeholder="请选择借调同行" disabled disabledColor="#fff"
							suffixIcon="arrow-right"></u--input>
					</view>
				</uni-forms-item>

				<uni-forms-item label="车牌号" required>
					<view @click.stop="showCarKeyboard=!showCarKeyboard">
						<u--input v-model="formData.carNo" placeholder="请输入车牌号" disabled disabledColor="#fff"
							maxlength="7"></u--input>
					</view>
				</uni-forms-item>

				<uni-forms-item label="车架号">
					<view>
						<u--input v-model="formData.vinNo" placeholder="请输入车架号"></u--input>
					</view>
				</uni-forms-item>

				<uni-forms-item label="借调开始时间" required label-width="100">
					<uni-datetime-picker type="datetime" v-model="formData.startTime" placeholder="请选择借调开始时间" />
				</uni-forms-item>

				<uni-forms-item label="借调单价" required>
					<view>
						<u--input v-model="formData.secondedUnitPrice" @input="check" type="digit"
							placeholder="请输入借调单价"></u--input>
					</view>
				</uni-forms-item>

				<uni-forms-item label="结算方式" required>
					<view @click="showSettlementType = true">
						<u--input v-model="formData.settlementWayStr" placeholder="请选择结算方式" disabled
							disabledColor="#fff" suffixIcon="arrow-right"></u--input>
					</view>
				</uni-forms-item>

				<uni-forms-item label="车辆初始化照片" labelPosition="top" labelWidth="300">
					<sr-upload ref="upload" maxCount="20" @uploadResult="uploadCar"></sr-upload>
				</uni-forms-item>

				<uni-forms-item label="备注" labelPosition="top">
					<view>
						<u--textarea v-model="formData.remark" placeholder="请输入200字以内的内容" count maxlength="200">
						</u--textarea>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>

		<button type="info" class="sub-btn" @click="confimCar">确认</button>

		<!-- 车牌号键盘 -->
		<u-keyboard ref="uKeyboard" mode="car" :show="showCarKeyboard" @change="keyboardChange" @backspace="backspace"
			@cancel="showCarKeyboard=false" @confirm="showCarKeyboard=false"></u-keyboard>
		<!-- 借调同行 -->
		<u-picker :show="showPeer" :columns="list1" keyName="name" closeOnClickOverlay @close="showPeer = false"
			@cancel="showPeer = false" title="请选择借入同行" confirmColor="#1573FF" @confirm="confimPeer"></u-picker>
		<!-- 结算方式 -->
		<u-picker :show="showSettlementType" :columns="list2" keyName="name" closeOnClickOverlay
			@close="showSettlementType = false" @cancel="showSettlementType = false" title="请选择结算方式"
			confirmColor="#1573FF" @confirm="confimSettlementType"></u-picker>
	</view>
</template>

<script>
	import * as secondedApi from '@/api/seconded-api.js';
	import srUpload from '@/components/upload/sr-upload.vue'
	var moment = require('@/utils/moment.js');
	import settings from '@/settings.js'
	export default {
		components: {
			srUpload
		},
		data() {
			return {
				type: 0,
				showCarKeyboard: false,
				showPeer: false,
				showSettlementType: false,
				id: '',
				formData: {
					orderNo: '',
					sameJobName: '',
					sameJobId: '',
					carNo: '',
					secondedType: 1,
					startTime: moment().format('YYYY-MM-DD HH:mm:ss'),
					estimateEndTime: '',
					estimateDay: '',
					totalRent: '',
					remark: '',
					settlementWay: 1,
					settlementWayStr: '',
					initialPicture: [],
					time: '',
					modelName: '',
					secondedUnitPrice:''
				},
				list1: [],
				list2: [
					[{
							name: '借调结束结算',
							id: 1
						},
						{
							name: '月末结算',
							id: 2
						}
					]
				]
			};
		},
		computed: {
			estimateDay() {
				let resultDay = '';
				if (!uni.$u.test.isEmpty(this.formData.startTime) && !uni.$u.test.isEmpty(this.formData.estimateEndTime)) {
					let m1 = moment(this.formData.startTime);
					let m2 = moment(this.formData.estimateEndTime);
					const diff = moment(m2).diff(moment(m1), 'seconds');
					//结束时间大于开始喀什
					if (diff > 0) {
						const diffHours = moment(m2).diff(moment(m1), 'hours');
						const day = Math.ceil(diffHours / 24);
						resultDay = day;
					} else {
						this.formData.estimateEndTime = '';
						uni.$u.toast('结束时间必须大于开始时间请重新选择');
					}
				} else {

				}
				return resultDay;

			}


		},
		onLoad(op) {
			if (op) {
				this.type = op.type;
				uni.setNavigationBarTitle({
					title: this.type == 1 ? '编辑借入车辆' : '借入车辆'
				})
			}

			if (this.type == 1) {
				this.id = op.id;
				this.getSecondedDetail();
			}

			this.getSecondedList();
			uni.$on('secondedOrder', (order) => {
				this.formData.orderNo = order.orderNo;
				this.formData.modelName = order.modelName;
				this.formData.startTime = order.rentalStartTime + ":00";
				this.formData.estimateEndTime = order.rentalEndTime + ":00";
				this.formData.time = order.rentalStartTime + '至' + order.rentalEndTime;

			})
		},
		methods: {
			// 选择订单
			chooseOrder() {
				if (this.type == 0) {
					uni.navigateTo({
						url: './carIn-order'
					})
				} else {
					uni.$u.toast('订单信息不可编辑')
				}

			},
			choosePeer() {
				if (this.type == 0) {
					this.showPeer = true;
				} else {
					uni.$u.toast('同行信息不可编辑')
				}
			},
			check(e) {
				//正则表达试
				e = (e.match(/^\d*(\.?\d{0,2})/g)[0]) || null
				this.$nextTick(() => {
					this.formData.totalRent = e;
				})
			},
			getSecondedDetail() {
				secondedApi.secondedDetail(this.id).then(res => {
					this.formData = res.data;
					this.formData.time = this.formData.rentalStartTime + '至' + this.formData.rentalEndTime;
					switch (this.formData.settlementWay) {
						case 1:
							this.formData.settlementWayStr = '借调结束结算';
							break;
						case 2:
							this.formData.settlementWayStr = '月末结算';
							break;
						case 3:
							this.formData.settlementWayStr = '借调前结算';
							break;
						default:
							break;
					}

					if (!this.$u.test.isEmpty(this.formData.initialPicture)) {
						this.$refs.upload.fileList = this.formData.initialPicture.map(item => {
							return {
								message: '',
								status: 'success',
								thumb: settings.baseImageUrl + item,
								type: 'image',
								url: item
							}

						})
					}
				});
			},
			getSecondedList() {
				var param = {
					pageNum: 1,
					pageSize: 1000,
				};
				secondedApi.peerList(this.toParams(param)).then(res => {
					this.list1 = [res.rows];
				}).catch(error => {

				})
			},

			// 租赁时间发生改变
			timeChange(e) {
				if (e.length == 1) {
					this.$u.toast('请选择结束时间');
					return
				}
				this.formData.startTime = e[0];
				this.formData.estimateEndTime = e[1];

			},
			// 选择同行
			confimPeer(e) {
				this.formData.sameJobId = e.value[0].id;
				this.formData.sameJobName = e.value[0].name;
				this.showPeer = false;
			},
			// 选择结算方式
			confimSettlementType(e) {
				this.formData.settlementWay = e.value[0].id;
				this.formData.settlementWayStr = e.value[0].name;
				this.showSettlementType = false;
			},
			//监听车牌号键盘改变
			keyboardChange(val) {
				this.formData.carNo += val;
			},
			//车牌号删除
			backspace() {
				if (this.formData.carNo) this.formData.carNo = this.formData.carNo.substr(0, this.formData.carNo.length -
					1);
			},
			// 上传车辆初始化图片
			uploadCar(data) {
				this.formData.initialPicture = data;
			},
			// 日期格式化
			parseTime(time, pattern) {
				if (arguments.length === 0 || !time) {
					return null;
				}
				const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
				let date;
				if (typeof time === 'object') {
					date = time;
				} else {
					if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
						time = parseInt(time);
					} else if (typeof time === 'string') {
						time = time
							.replace(new RegExp(/-/gm), '/')
							.replace('T', ' ')
							.replace(new RegExp(/\.[\d]{3}/gm), '');
					}
					if (typeof time === 'number' && time.toString().length === 10) {
						time = time * 1000;
					}
					date = new Date(time);
				}
				const formatObj = {
					y: date.getFullYear(),
					m: date.getMonth() + 1,
					d: date.getDate(),
					h: date.getHours(),
					i: date.getMinutes(),
					s: date.getSeconds(),
					a: date.getDay()
				};
				const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
					let value = formatObj[key];
					// Note: getDay() returns 0 on Sunday
					if (key === 'a') {
						return ['日', '一', '二', '三', '四', '五', '六'][value];
					}
					if (result.length > 0 && value < 10) {
						value = '0' + value;
					}
					return value || 0;
				});
				return time_str;
			},
			// 确认
			confimCar() {

				if (uni.$u.test.isEmpty(this.formData.orderNo)) {
					uni.$u.toast('请选择订单');
					return
				} else if (uni.$u.test.isEmpty(this.formData.sameJobId)) {
					uni.$u.toast('请选择借调同行');
					return
				} else if (uni.$u.test.isEmpty(this.formData.carNo)) {
					uni.$u.toast('请输入车牌号');
					return
				} else if (uni.$u.test.isEmpty(this.formData.secondedUnitPrice)) {
					uni.$u.toast('请输入借调单价');
					return
				} else if (uni.$u.test.isEmpty(this.formData.startTime)) {
					uni.$u.toast('借调开始时间不能为空,请选择');
					return
				} else if (uni.$u.test.isEmpty(this.formData.settlementWay)) {
					uni.$u.toast('请选择结算方式');
					return
				} else {
					this.formData.estimateDay = this.estimateDay;
					if (this.type == 1) { //编辑
						secondedApi.editSeconded(this.formData).then(res => {
							uni.$emit("refreshSecondedList");
							this.$u.toast('修改成功')
							uni.navigateBack({
								animationDuration: 300,
								delta: 1
							})
						})
					} else { //新增
						secondedApi.addSeconded(this.formData).then(res => {
							uni.$emit("refreshSecondedList");
							this.$u.toast('借调成功')
							uni.navigateBack({
								animationDuration: 300,
								delta: 1
							})
						})
					}


				}


			}
		}
	};
</script>

<style lang="scss" scoped>
	.formContainer {
		margin: 40rpx 20rpx;
		padding: 24rpx;
		background-color: #fff;
		box-shadow: 0px 4rpx 16rpx 0px rgba(1, 10, 18, 0.1);
		border-radius: 16rpx;
	}
</style>